package com.ssy.lingxi.contract.serviceimpl;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.contract.constant.SignConstant;
import com.ssy.lingxi.contract.entity.SignatureAccount;
import com.ssy.lingxi.contract.entity.SignatureAuth;
import com.ssy.lingxi.contract.entity.SignatureAuthLog;
import com.ssy.lingxi.contract.entity.SignatureOrganization;
import com.ssy.lingxi.contract.esign.api.SignApi;
import com.ssy.lingxi.contract.esign.constant.EsignConstants;
import com.ssy.lingxi.contract.esign.exception.EsignException;
import com.ssy.lingxi.contract.esign.request.*;
import com.ssy.lingxi.contract.esign.response.*;
import com.ssy.lingxi.contract.model.bo.sign.SignAuthNotifyBO;
import com.ssy.lingxi.contract.model.constant.CommonBooleanEnum;
import com.ssy.lingxi.contract.model.constant.sign.SignatureAuthStateEnum;
import com.ssy.lingxi.contract.model.constant.sign.SignatureAuthStepEnum;
import com.ssy.lingxi.contract.model.constant.sign.SignatureAuthTypeEnum;
import com.ssy.lingxi.contract.model.constant.sign.VerifyTypeEnum;
import com.ssy.lingxi.contract.model.vo.sign.request.*;
import com.ssy.lingxi.contract.model.vo.sign.response.FaceVerifyResponse;
import com.ssy.lingxi.contract.model.vo.sign.response.SignatureApplyResponse;
import com.ssy.lingxi.contract.model.vo.sign.response.SignatureAuthResponse;
import com.ssy.lingxi.contract.model.vo.sign.response.SignatureAuthStateResponse;
import com.ssy.lingxi.contract.repository.SignatureAccountRepository;
import com.ssy.lingxi.contract.repository.SignatureAuthLogRepository;
import com.ssy.lingxi.contract.repository.SignatureAuthRepository;
import com.ssy.lingxi.contract.repository.SignatureOrganizationRepository;
import com.ssy.lingxi.contract.service.ISignatureAccountService;
import com.ssy.lingxi.contract.service.ISignatureAuthService;
import com.ssy.lingxi.contract.service.ISignatureOrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 电子签章服认证务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/9/1
 */
@Slf4j
@Service
public class SignatureAuthServiceImpl implements ISignatureAuthService {

    @Resource
    private SignatureAuthRepository signatureAuthRepository;
    @Resource
    private SignatureAuthLogRepository signatureAuthLogRepository;
    @Resource
    private ISignatureAccountService signatureAccountService;
    @Resource
    private ISignatureOrganizationService signatureOrganizationService;
    @Resource
    private SignatureAccountRepository signatureAccountRepository;
    @Resource
    private SignatureOrganizationRepository signatureOrganizationRepository;
    @Resource
    private SignApi signApi;

    @Override
    public Wrapper<SignatureAuthResponse> getSignatureDetail(UserLoginCacheDTO sysUser) {
        SignatureAuthResponse signatureAuthResponse = new SignatureAuthResponse();

        SignatureAuth signatureAuth = signatureAuthRepository.findByMemberId(sysUser.getMemberId());
        if (Objects.isNull(signatureAuth)) {
            signatureAuthResponse.setState(SignatureAuthStateEnum.NOT_APPLYING.getCode());
            return Wrapper.success(signatureAuthResponse);
        }

        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(signatureAuth.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        signatureAuthResponse.setState(signatureAuthLog.getState());
        signatureAuthResponse.setStep(signatureAuthLog.getStep());
        signatureAuthResponse.setVerifyType(signatureAuthLog.getVerifyType());
        signatureAuthResponse.setAuthType(signatureAuthLog.getAuthType());


        if (SignatureAuthTypeEnum.LEGAL_PERSON.getCode().equals(signatureAuthLog.getAuthType())
                || SignatureAuthTypeEnum.AGENT.getCode().equals(signatureAuthLog.getAuthType())) {
            // 企业认证
            SignatureOrganization signatureOrganization = signatureOrganizationRepository.findByOrgId(signatureAuthLog.getOrgId());
            if (!Objects.isNull(signatureOrganization)) {
                signatureAuthResponse.setOrgName(signatureOrganization.getName());
                signatureAuthResponse.setOrgCode(signatureOrganization.getIdNumber());
                signatureAuthResponse.setLegalRepName(signatureOrganization.getOrgLegalName());
                signatureAuthResponse.setLegalRepIdNo(signatureOrganization.getOrgLegalIdNumber());
                signatureAuthResponse.setLegalRepMobile(signatureOrganization.getOrgLegalMobile());
            }
        } else if (SignatureAuthTypeEnum.PERSONAL.getCode().equals(signatureAuthLog.getAuthType())){
            // 个人认证
            SignatureAccount signatureAccount = signatureAccountRepository.findByAccountId(signatureAuthLog.getAccountId());
            if (!Objects.isNull(signatureAccount)) {
                signatureAuthResponse.setLegalRepName(signatureAccount.getName());
                signatureAuthResponse.setLegalRepIdNo(signatureAccount.getIdNumber());
                signatureAuthResponse.setLegalRepMobile(signatureAccount.getMobile());
            }
        }

        return Wrapper.success(signatureAuthResponse);
    }

    @Override
    public Wrapper<SignatureAuthStateResponse> getAuthState(UserLoginCacheDTO sysUser) {
        SignatureAuthStateResponse response = new SignatureAuthStateResponse();

        SignatureAuth signatureAuth = signatureAuthRepository.findByMemberId(sysUser.getMemberId());
        if (Objects.isNull(signatureAuth)) {
            response.setState(CommonBooleanEnum.NO.getCode());
        } else {
            response.setMemberId(sysUser.getMemberId());
            response.setState(signatureAuth.getState());
        }

        return Wrapper.success(response);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<SignatureApplyResponse> signatureApply(UserLoginCacheDTO sysUser) {
        SignatureAuth signatureAuth = signatureAuthRepository.findByMemberId(sysUser.getMemberId());
        if (Objects.isNull(signatureAuth)) {
            signatureAuth = new SignatureAuth();
            signatureAuth.setMemberId(sysUser.getMemberId());
            signatureAuthRepository.saveAndFlush(signatureAuth);
        }

        // 申请记录
        SignatureAuthLog saveEntity = new SignatureAuthLog();
        saveEntity.setMemberId(sysUser.getMemberId());
        // 申请步骤
        saveEntity.setStep(SignatureAuthStepEnum.MESSAGE_VERIFY.getCode());
        // 申请状态
        saveEntity.setState(SignatureAuthStateEnum.NOT_APPLYING.getCode());
        saveEntity.setCreateTime(System.currentTimeMillis());
        signatureAuthLogRepository.saveAndFlush(saveEntity);

        // 当前会员id
        signatureAuth.setMemberId(sysUser.getMemberId());
        // 关联申请认证
        signatureAuth.setSignatureAuthLogId(saveEntity.getId());
        // 认证状态
        signatureAuth.setState(CommonBooleanEnum.NO.getCode());
        signatureAuthRepository.saveAndFlush(signatureAuth);

        // 返回结果
        SignatureApplyResponse response = new SignatureApplyResponse();
        response.setSignatureAuthLogId(saveEntity.getId());
        response.setStep(SignatureAuthStepEnum.MESSAGE_VERIFY.getCode());
        return Wrapper.success(response);
    }

    @Override
    public Wrapper<Void> legalRepAuth(LegalRepAuthAuthRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 创建个人账号
        String accountId;
        if (Objects.isNull(signatureAuthLog.getAccountId())) {
            try {
                accountId = signatureAccountService.createAccount(request.getLegalRepIdNo(), request.getLegalRepName(), request.getLegalRepMobile());
            } catch (EsignException e) {
                log.error("签章认证创建个人账号: {}", e.getError());
                return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
            }

            // 保存个人账号id
            signatureAuthLog.setAccountId(accountId);
            signatureAuthLogRepository.saveAndFlush(signatureAuthLog);
        } else {
            accountId = signatureAuthLog.getAccountId();
        }

        // 创建企业账号
        String orgId;
        if (Objects.isNull(signatureAuthLog.getOrgId())) {
            try {
                orgId = signatureOrganizationService.createAccount(accountId, request.getOrgCode(), request.getOrgName(), request.getLegalRepIdNo(), request.getLegalRepName(), request.getLegalRepMobile());
            } catch (EsignException e) {
                log.error("签章认证创建机构账号: {}", e.getError());
                return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
            }

            // 保存机构账号id
            signatureAuthLog.setOrgId(orgId);
            signatureAuthLogRepository.saveAndFlush(signatureAuthLog);
        }

        // 保存认证记录信息
        signatureAuthLog.setAuthType(request.getAuthType());
        signatureAuthLog.setStep(SignatureAuthStepEnum.CHOOSE_AUTH_TYPE.getCode());
        signatureAuthLog.setState(SignatureAuthStateEnum.APPLYING.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        return Wrapper.success();
    }

    @Override
    public Wrapper<Void> agentAuth(AgentAuthRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 创建个人账号
        String accountId;
        if (Objects.isNull(signatureAuthLog.getAccountId())) {
            try {
                accountId = signatureAccountService.createAccount(request.getLegalRepIdNo(), request.getLegalRepName(), request.getLegalRepMobile());
            } catch (EsignException e) {
                log.error("签章认证创建个人账号: {}", e.getError());
                return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
            }

            // 保存个人账号id
            signatureAuthLog.setAccountId(accountId);
            signatureAuthLogRepository.saveAndFlush(signatureAuthLog);
        } else {
            accountId = signatureAuthLog.getAccountId();
        }

        // 创建企业账号
        String orgId;
        if (Objects.isNull(signatureAuthLog.getOrgId())) {
            try {
                orgId = signatureOrganizationService.createAccount(accountId, request.getOrgCode(), request.getOrgName(), request.getLegalRepIdNo(), request.getLegalRepName(), request.getLegalRepMobile());
            } catch (EsignException e) {
                log.error("签章认证创建机构账号: {}", e.getError());
                return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
            }

            // 保存机构账号id
            signatureAuthLog.setOrgId(orgId);
            signatureAuthLogRepository.saveAndFlush(signatureAuthLog);
        }

        // 保存认证记录信息
        signatureAuthLog.setAuthType(request.getAuthType());
        signatureAuthLog.setStep(SignatureAuthStepEnum.CHOOSE_AUTH_TYPE.getCode());
        signatureAuthLog.setState(SignatureAuthStateEnum.APPLYING.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        return Wrapper.success();
    }

    @Override
    public Wrapper<Void> personalAuth(PersonalAuthRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 创建个人账号
        String accountId;
        if (Objects.isNull(signatureAuthLog.getAccountId())) {
            try {
                accountId = signatureAccountService.createAccount(request.getTransactorIdNumber(), request.getTransactorName(), request.getTransactorMobile());
            } catch (EsignException e) {
                log.error("签章认证创建个人账号: {}", e.getError());
                return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
            }

            // 保存个人账号id
            signatureAuthLog.setAccountId(accountId);
            signatureAuthLogRepository.saveAndFlush(signatureAuthLog);
        }

        // 保存认证记录信息
        signatureAuthLog.setAuthType(SignatureAuthTypeEnum.PERSONAL.getCode());
        signatureAuthLog.setStep(SignatureAuthStepEnum.CHOOSE_AUTH_TYPE.getCode());
        signatureAuthLog.setState(SignatureAuthStateEnum.APPLYING.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        return Wrapper.success();
    }

    @Override
    public Wrapper<Void> paymentVerifyCreate(PaymentVerifyCreateRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 认证流程id
        String flowId;
        try {
            // 查询企业信息
            OrgAccountDetailResponse orgAccountDetail = signApi.account().orgAccountDetail(signatureAuthLog.getOrgId());

            // 企业信息认证
            flowId = orgRealNameAuth(orgAccountDetail.getName(), orgAccountDetail.getIdNumber(), orgAccountDetail.getOrgLegalName(), orgAccountDetail.getOrgLegalIdNumber());

            // 查询打款银行信息
            SubbranchDetailResponse response = signApi.enterpriseAuth().subbranchDetail(flowId, request.getBankName());
            List<SubbranchDetailResponse.BankDetail> bankList = response.getList();
            if (CollectionUtils.isEmpty(bankList)) {
                return Wrapper.fail(ResponseCode.CONTRACT_BANK_NOT_FOUND);
            }
            SubbranchDetailResponse.BankDetail bankDetail = bankList.get(0);

            // 发起随机打款认证
            TransferRandomAmountRequest randomAmountRequest = TransferRandomAmountRequest.builder()
                    .flowId(flowId)
                    .bank(bankDetail.getBank())
                    .province(bankDetail.getProvince())
                    .city(bankDetail.getCity())
                    .subbranch(bankDetail.getBankName())
                    .cnapsCode(bankDetail.getCnapsCode())
                    .cardNo(request.getCardNo())
                    .notifyUrl(signApi.getProperties().getNotifyUrl() + SignConstant.transferRandomAmountUri)
                    .build();
            signApi.enterpriseAuth().transferRandomAmount(randomAmountRequest);
        } catch (EsignException e) {
            log.error("e签宝对公打款认证: {}", e.getError());
            return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
        }

        // 保存认证记录信息
        signatureAuthLog.setFlowId(flowId);
        signatureAuthLog.setVerifyType(VerifyTypeEnum.PAYMENT.getCode());
        signatureAuthLog.setStep(SignatureAuthStepEnum.AUTH.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        return Wrapper.success();
    }

    @Override
    public Wrapper<FaceVerifyResponse> paymentVerifyAmount(PaymentVerifyAmountRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        try {
            // 随机打款校验
            signApi.enterpriseAuth().verifyRandomAmount(signatureAuthLog.getFlowId(), request.getAmount());
        } catch (EsignException e) {
            log.error("e签宝对公打款校验:{}", e.getError());
            return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
        }

        return Wrapper.success();
    }

    @Override
    public Wrapper<Void> legalRepSignVerify(LegalRepSignVerifyRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 认证流程id
        String flowId;
        try {
            // 查询企业信息
            OrgAccountDetailResponse orgAccountDetail = signApi.account().orgAccountDetail(signatureAuthLog.getOrgId());

            // 企业信息认证
            flowId = orgRealNameAuth(orgAccountDetail.getName(), orgAccountDetail.getIdNumber(), orgAccountDetail.getOrgLegalName(), orgAccountDetail.getOrgLegalIdNumber());

            // 发起法人授权签署
            LegalRepSignCheckAuthRequest legalRepSignCheckAuthRequest = LegalRepSignCheckAuthRequest.builder()
                    .flowId(flowId)
                    .agentIdNo(request.getAgentIdNo())
                    .agentName(request.getAgentName())
                    .mobileNo(request.getLegalRepMobile())
                    .build();
            signApi.enterpriseAuth().legalRepSignCheckAuth(legalRepSignCheckAuthRequest);
        } catch (EsignException e) {
            log.error("e签宝授权签署: {}", e.getError());
            return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
        }

        // 保存认证记录信息
        signatureAuthLog.setFlowId(flowId);
        signatureAuthLog.setVerifyType(VerifyTypeEnum.LEGAL_REP_SIGN.getCode());
        signatureAuthLog.setStep(SignatureAuthStepEnum.AUTH.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        return Wrapper.success();
    }

    @Override
    public Wrapper<FaceVerifyResponse> faceVerify(FaceVerifyRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 认证流程id
        String flowId;
        // 认证链接
        String authUrl;
        // 链接时效
        Long expire;
        try {
            // TODO 跳转地址, 回调逻辑
            FaceRealNameAuthRequest faceRealNameAuthRequest = FaceRealNameAuthRequest.builder()
                    .accountId(signatureAuthLog.getAccountId())
                    .faceauthMode(EsignConstants.faceauthMode.ZHIMACREDIT)
                    .callbackUrl(signApi.getProperties().getNotifyUrl() + Constants.SIGN_AUTH_ACTION + SignConstant.appScheme)
                    .notifyUrl(signApi.getProperties().getNotifyUrl() + SignConstant.faceAuthUri)
                    .build();

            // 发起刷脸认证 TODO 有时效
            FaceAuthResponse faceAuthResponse = signApi.personalAuth().faceRealNameAuth(faceRealNameAuthRequest);
            expire = faceAuthResponse.getExpire();
            authUrl = faceAuthResponse.getAuthUrl();
            flowId = faceAuthResponse.getFlowId();

        } catch (EsignException e) {
            log.error("e签宝刷脸认证: {}", e.getError());
            return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
        }

        // 保存认证记录信息
        signatureAuthLog.setFlowId(flowId);
        signatureAuthLog.setVerifyType(VerifyTypeEnum.ALIPAY.getCode());
        signatureAuthLog.setStep(SignatureAuthStepEnum.AUTH.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        // 返回信息
        FaceVerifyResponse response = new FaceVerifyResponse();
        response.setAuthUrl(authUrl);
        response.setExpire(expire);
        return Wrapper.success(response);
    }

    @Override
    public Wrapper<Void> mobileVerify(MobileVerifyRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }

        // 认证流程id
        String flowId;
        try {
            TelecomRealNameAuthRequest telecomAuthRequest = TelecomRealNameAuthRequest.builder()
                    .accountId(signatureAuthLog.getAccountId())
                    .mobileNo(request.getMobileNo())
                    .notifyUrl(signApi.getProperties().getNotifyUrl() + SignConstant.telecomAuthUri)
                    .build();

            // 发起运营商认证
            TelecomAuthResponse telecomAuthResponse = signApi.personalAuth().telecomRealNameAuth(telecomAuthRequest);
            flowId = telecomAuthResponse.getFlowId();
        } catch (EsignException e) {
            log.error("e签宝运营商认证: {}", e.getError());
            return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
        }

        // 保存认证记录信息
        signatureAuthLog.setFlowId(flowId);
        signatureAuthLog.setVerifyType(VerifyTypeEnum.MOBILE.getCode());
        signatureAuthLog.setStep(SignatureAuthStepEnum.AUTH.getCode());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        return Wrapper.success();
    }

    @Override
    public Wrapper<Void> mobileVerifyCode(MobileVerifyCodeRequest request, UserLoginCacheDTO sysUser) {
        // 查询认证申请记录
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findById(request.getSignatureAuthLogId()).orElse(null);
        if (Objects.isNull(signatureAuthLog)) {
            return Wrapper.fail(ResponseCode.CONTRACT_DATA_RECORDS_DOES_NOT_EXIST);
        }


        if (Objects.isNull(signatureAuthLog.getFlowId())) {
            return Wrapper.fail(ResponseCode.CONTRACT_SIGNATURE_NOT_FOUND);
        }

        try {
            // 发起运营商短息验证码校验
            signApi.personalAuth().telecomAuthCode(signatureAuthLog.getFlowId(), request.getAuthcode());
        } catch (EsignException e) {
            log.error("e签宝运营商认证校验: {}", e.getError());
            return Wrapper.fail(ResponseCode.CONTRACT_ESIGN_FAIL, e.getError().getErrMsg());
        }

        return Wrapper.success();
    }

    @Override
    public boolean verifySuccess(SignAuthNotifyBO notifyBO) {
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findByFlowId(notifyBO.getFlowId());
        if (Objects.isNull(signatureAuthLog)) {
            return false;
        }
        // 修改签章认证记录
        signatureAuthLog.setState(SignatureAuthStateEnum.APPROVE.getCode());
        signatureAuthLog.setDescription(notifyBO.getStatusDescription());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        // 修改签章认证
        SignatureAuth signatureAuth = signatureAuthRepository.findBySignatureAuthLogId(signatureAuthLog.getId());
        if (Objects.isNull(signatureAuth)) {
            return false;
        }

        signatureAuth.setState(CommonBooleanEnum.YES.getCode());
        signatureAuthRepository.saveAndFlush(signatureAuth);

        // 修改账号信息
        if (SignatureAuthTypeEnum.LEGAL_PERSON.getCode().equals(signatureAuthLog.getAuthType())
                || SignatureAuthTypeEnum.AGENT.getCode().equals(signatureAuthLog.getAuthType())) {
            SignatureOrganization signatureOrganization = signatureOrganizationRepository.findByOrgId(signatureAuthLog.getOrgId());
            if (!Objects.isNull(signatureOrganization)) {
                signatureOrganization.setState(CommonBooleanEnum.YES.getCode());
                signatureOrganizationRepository.saveAndFlush(signatureOrganization);
            }
        } else if (SignatureAuthTypeEnum.PERSONAL.getCode().equals(signatureAuthLog.getAuthType())) {
            SignatureAccount signatureAccount = signatureAccountRepository.findByAccountId(signatureAuthLog.getAccountId());
            if (!Objects.isNull(signatureAccount)) {
                signatureAccount.setState(CommonBooleanEnum.YES.getCode());
                signatureAccountRepository.saveAndFlush(signatureAccount);
            }
        }

        return true;
    }

    @Override
    public boolean verifyFail(SignAuthNotifyBO notifyBO) {
        SignatureAuthLog signatureAuthLog = signatureAuthLogRepository.findByFlowId(notifyBO.getFlowId());
        if (Objects.isNull(signatureAuthLog)) {
            return false;
        }

        // 修改签章认证记录
        signatureAuthLog.setState(SignatureAuthStateEnum.REJECT.getCode());
        signatureAuthLog.setDescription(notifyBO.getStatusDescription());
        signatureAuthLogRepository.saveAndFlush(signatureAuthLog);

        // 修改签章认证
        SignatureAuth signatureAuth = signatureAuthRepository.findBySignatureAuthLogId(signatureAuthLog.getId());
        if (Objects.isNull(signatureAuth)) {
            return false;
        }

        signatureAuth.setState(CommonBooleanEnum.NO.getCode());
        signatureAuthRepository.saveAndFlush(signatureAuth);

        return true;
    }

    /**
     * 企业信息认证(必须填写4要素,否则无法进行法人授权签署认证)
     * @param orgName 组织名称
     * @param orgCode 组织编码
     * @param legalRepName 合法代表姓名
     * @param legalRepIdNo 合法代表编码
     * @return 企业信息认证(必须填写4要素,否则无法进行法人授权签署认证)
     * @throws EsignException e签宝异常
     */
    private String orgRealNameAuth(String orgName, String orgCode, String legalRepName, String legalRepIdNo) throws EsignException {
//        OrgRealName4AuthRequest authRequest = OrgRealName4AuthRequest.builder()
//                .name(orgName)
//                .orgCode(orgCode)
//                .legalRepName(legalRepName)
//                .legalRepIdNo(legalRepIdNo)
//                .notifyUrl(SignConstant.organizationAuthUri)
//                .build();
//        OrgAuthResponse orgAuthResponse = signApi.enterpriseAuth().check4Auth(authRequest);

        OrgCheck3AuthRequest authRequest = OrgCheck3AuthRequest.builder()
                .name(orgName)
                .orgCode(orgCode)
                .legalRepName(legalRepName)
                .notifyUrl(signApi.getProperties().getNotifyUrl() + SignConstant.organizationAuthUri)
                .build();
        OrgAuthResponse orgAuthResponse = signApi.enterpriseAuth().check3Auth(authRequest);
        return orgAuthResponse.getFlowId();
    }
}